package com.wangshouyu.mp.pay.order;

import com.wangshouyu.mp.pay.common.constant.UrlConstant;
import com.wangshouyu.mp.pay.common.utils.HttpUtils;
import com.wangshouyu.mp.pay.common.utils.SignUtils;
import com.wangshouyu.mp.pay.common.utils.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 王守钰
 * @description 订单工具类
 * @date 2020/8/13 14:36
 */
public class OrderUtils {

    private static Logger log = LoggerFactory.getLogger(OrderUtils.class);

    private OrderUtils(){}

    /**
     * 查询订单
     * @param request 查询订单请求
     * @return 查询订单结果
     */
    public static QueryOrderResponse query(QueryOrderRequest request){
        // 设置签名
        request.setSign(SignUtils.sign(request, request.getSignType()));
        // 转换请求xml
        String requestXml = XmlUtils.object2Xml(request);
        log.info("wechat query order request xml:{}", requestXml);
        // 发起请求
        try {
            String responseXml = HttpUtils.postXml(UrlConstant.QUERY_ORDER_URL, requestXml);
            log.info("wechat query order response xml:{}", responseXml);
            return XmlUtils.xml2Bean(requestXml, QueryOrderResponse.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new QueryOrderException(e);
        }
    }

    /**
     * 关闭订单
     * @param request 关闭订单请求
     * @return 关闭订单响应结果
     */
    public static CloseOrderResponse close(CloseOrderRequest request){
        // 设置签名
        request.setSign(SignUtils.sign(request, request.getSignType()));
        // 转换请求xml
        String requestXml = XmlUtils.object2Xml(request);
        log.info("wechat close order request xml:{}", requestXml);
        // 发起请求
        try {
            String responseXml = HttpUtils.postXml(UrlConstant.CLOSE_ORDER_URL, requestXml);
            log.info("wechat close order response xml:{}", responseXml);
            return XmlUtils.xml2Bean(requestXml, CloseOrderResponse.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new CloseOrderException(e);
        }
    }
}
